<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template v-slot:before>
          共{{ total }}条记录
        </template>
        <template v-slot:after>
          <!-- 添加导入点击事件 -->
          <el-button size="small" type="warning" @click="importFn">导入</el-button>
          <el-button size="small" type="danger" @click="exportFn">导出</el-button>
          <el-button size="small" type="primary" @click="addFn">新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <el-table :data="employees" border>
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="staffPhoto" label="头像" sortable="">
            <template v-slot="{row}">
              <img v-imgError="require('../../assets/common/bigUserHeader.png')" style="width:100px" :src="row.staffPhoto" alt="">
            </template>
          </el-table-column>
          <!-- row是表格组件 通过作用域插槽返回给我们的数据 -->
          <!-- <el-table-column prop="formOfEmployment" label="聘用形式" sortable="">
            <template v-slot="{row}">
              {{ row.formOfEmployment===1?'正式':'非正式' }}
            </template>
          </el-table-column> -->
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template v-slot="{row}">
              <!-- 账户状态，返回0和1,0表示关闭，1表示启动 -->
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#666"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="toDetail(row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <!-- 给角色按钮的事件处理函数传员工id，再通过ref属性调用子组件的函数，从而获取员工信息 -->
              <el-button type="text" size="small" @click="roleAssignFn(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 设置分页器属性 -->
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="size"
            @current-change="currentChangeFn"
          />
        </el-row>
      </el-card>

      <!-- 引入注册 使用组件，然后使用showDialog变量控制弹窗显示 -->
      <AddEmployee :show-dialog.sync="showDialog" @updateEvent="getEmployees" />
      <AssignRole ref="AssignRole" :visible-dialog.sync="visibleDialog" />
    </div>
  </div>
</template>

<script>
import { getEmployees, delEmployee } from '@/api/employees'
import employeesData from '@/api/constant/employees.js'
import AddEmployee from './components/add-employee.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import AssignRole from './components/assign-role.vue'
export default {
  components: { AddEmployee, AssignRole },
  data() {
    return {
      page: 1,
      size: 5,
      total: 0,
      employees: [],
      // 一开始弹窗隐藏
      showDialog: false,
      visibleDialog: false
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    // 分配角色
    roleAssignFn(id) {
      this.visibleDialog = true
      // 调用子组件中获取员工信息的函数
      this.$refs.AssignRole.getUserDetail(id)
    },
    // 跳转到详情页面
    toDetail(id) {
      this.$router.push({
        path: '/employees/detail/' + id
      })
    },
    // 导出
    async exportFn() {
      const res = await getEmployees({
        page: 1, // 请求第一页
        size: this.total // 请求所有数据
      })
      const data = res.rows.map(item => {
        return this.objToArr(item)
      })
      const header = ['手机号', '姓名', '入职日期', '转正日期', '工号']
      // const data = [
      //   ['13234345656', '小明', '2022-01-02', '2022-03-02', '12345'],
      //   ['13234347878', '小炮', '2022-01-02', '2022-03-02', '12345']
      // ]

      // 导出组件
      export_json_to_excel({
        header: header,
        data: data
      })
    },
    objToArr(item) {
      const arr = []
      const dic = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      for (const key in dic) {
        // key：是对象中的属性名
        const enKey = dic[key] // 根据中文的key找到对应英文的key值
        // 根据英文属性名从item中找到对应的值
        const value = item[enKey]
        // 把获取到值添加到arr数组中
        arr.push(value)
      }
      // 处理
      return arr
    },
    // 导入时跳转路由
    importFn() {
      this.$router.push('/import')
    },
    // 删除
    delFn(id) {
      this.$confirm('是否确定删除？', '删除', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        // 调用删除接口
        await delEmployee(id)
        // 重新渲染数据
        this.getEmployees()
      }).catch((err) => {
        console.log('取消', err)
      })
    },
    addFn() {
      // 点击新增时弹出新增员工弹窗
      this.showDialog = true
    },
    // 格式化聘用形势
    formatEmployment(row) {
      // console.log(72, row.formOfEmployment)
      // 注意：函数返回什么内容，那么表格中就显示什么内容
      // return row.formOfEmployment === 1 ? '正式' : '非正式'
      // console.log(81, employeesData.hireType)
      // 数据类型不一样，所以要转为数字类型Number
      const obj = employeesData.hireType.find(item => Number(item.id) === Number(row.formOfEmployment))
      // console.log(obj, row.formOfEmployment, employeesData.hireType)
      return obj ? obj.value : '未知'
    },
    async getEmployees() {
      const res = await getEmployees({
        page: this.page,
        size: this.size
      })
      this.employees = res.rows
      this.total = res.total
    },
    // 页码发生改变时触发
    currentChangeFn(page) {
      this.page = page
      this.getEmployees()
    }
  }

}
</script>

<style>

</style>
